package com.tt.utils.wordUtils.renderplicy;

import cn.hutool.core.collection.CollectionUtil;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.tt.utils.wordUtils.entity.TableContent;
import com.tt.utils.wordUtils.utils.BaseWordUtiils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;


/**
 * @Title: TableRenderPolicy
 * @Author zl
 * @Package com.oberyun.goHAZOP.utils.wordUtils
 * @Date 2025/9/4 18:07
 * @description: 表格渲染（支持动态表头）
 */
public class TableRenderPolicy extends AbstractRenderPolicy<TableContent.TableBody> {

    @Override
    protected boolean validate(TableContent.TableBody data) {
        return data != null;
    }

    @Override
    public void doRender(RenderContext<TableContent.TableBody> context) throws Exception {
        TableContent.TableBody tableData = context.getData();
        XWPFParagraph paragraph = (XWPFParagraph) context.getRun().getParent();
        XWPFTableCell templateCell = (XWPFTableCell) paragraph.getBody();
        XWPFTable table = templateCell.getTableRow().getTable();

        // 获取当前行索引
        int templateRowIndex = table.getRows().indexOf(templateCell.getTableRow());

        // 先移除模板行
        table.removeRow(templateRowIndex);

        // 添加动态表头
        if (CollectionUtil.isNotEmpty(tableData.getTitles())) {
            addTableHeader(table, tableData.getTitles());
        }

        // 添加表格数据行
        if (CollectionUtil.isNotEmpty(tableData.getBody())) {
            if(CollectionUtil.isNotEmpty(tableData.getTitles())){
                addTableBody(table, tableData.getBody(), tableData.getColumnCount());
            }else{
                addTableBody(table, tableData.getBody(), tableData.getColumnCount());
            }
        }
        //如果表头不为空是设置单元格样式
        if(CollectionUtil.isNotEmpty(tableData.getTitles())){
            // 设置表格样式
            setTableStyle(table);
        }
    }

    /**
     * 添加表头行
     */
    private void addTableHeader(XWPFTable table, List<TableContent.TableTitleData> titles) {
        if (CollectionUtil.isEmpty(titles)) {
            return;
        }

        // 创建表头行
        XWPFTableRow headerRow = table.createRow();

        for (int i = 0; i < titles.size(); i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            if (cell == null) {
                cell = headerRow.createCell();
            }

            // 设置表头样式
            setHeaderCellStyle(cell,titles.get(i).getContent());

            // 设置单元格宽度（可选）
            setCellWidth(cell, 0.3); // 约2cm宽度
        }
    }

    /**
     * 添加表格数据行
     */
    private void addTableBody(XWPFTable table, List<List<TableContent.TableCellData>> bodyData, int columnCount) {
        if (CollectionUtil.isEmpty(bodyData)) {
            return;
        }

        for (int i = 0; i < bodyData.size(); i++) {
            List<TableContent.TableCellData> rowData = bodyData.get(i);
            XWPFTableRow dataRow = table.createRow();

            // 确保有足够的列
            while (dataRow.getTableCells().size() < columnCount) {
                dataRow.createCell();
            }

            for (int j = 0; j < columnCount; j++) {
                XWPFTableCell cell = dataRow.getCell(j);
                TableContent.TableCellData cellData = rowData.get(j);
                if (j < rowData.size()) {
                    renderCellContent(cell, cellData);
                } else {
                    // 如果数据不足，设置空内容
                    cell.setText("");
                }

                // 设置数据单元格样式
                setDataCellStyle(cell,cellData.getStjc());
            }
        }
    }

    /**
     * 渲染单元格内容
     */
    private void renderCellContent(XWPFTableCell cell, TableContent.TableCellData cellData) {
        if (cellData == null || cellData.getContent() == null) {
            cell.setText("");
            return;
        }
        // 清除现有内容
        for (int i = cell.getParagraphs().size() - 1; i >= 0; i--) {
            cell.removeParagraph(i);
        }

        // 创建新段落
        XWPFParagraph paragraph = cell.addParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER); // 默认居中
        XWPFRun run = paragraph.createRun();
        // 设置文本内容
        switch (cellData.getType()){
            case 1:
                BaseWordUtiils.appendImage(cellData.getContent(), run);
                break;
            case 2:
                run.setText(cellData.getContent().toString());
                cell.setColor(cellData.getContent().toString().replace("#", ""));
                break;
            case 3:
                String imageUrl = cellData.getContent().toString();
                String name = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
                BaseWordUtiils.appendExternalHyperlink(imageUrl, name, paragraph);
                break;
            default:
                run.setText(cellData.getContent().toString());
                break;
        }
        // 设置垂直对齐
        cell.setVerticalAlignment(cellData.getVerticalAlignment());

    }

    /**
     * 设置表头单元格样式
     */
    private void setHeaderCellStyle(XWPFTableCell cell, String content) {
        // 设置背景色
        //cell.setColor("4472C4");
        // 设置文本样式
        CTTc ctTc = cell.getCTTc();
        CTP ctP = (ctTc.sizeOfPArray() == 0) ?ctTc.addNewP() : ctTc.getPArray(0);
        if (cell.getParagraphs().size() > 0) {
            XWPFParagraph paragraph = cell.getParagraph(ctP);
            XWPFRun run = paragraph.createRun();
            run.setBold(true);
            run.setText(content);
            run.setColor("000000");
            run.setFontSize(12);
            run.setFontFamily("宋体");
        }

        // 设置垂直居中
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);

        // 设置水平居中
        setCellHorizontalAlignment(cell, STJc.CENTER);

        // 设置边框
        setCellBorder(cell);
    }

    /**
     * 设置数据单元格样式
     */
    private void setDataCellStyle(XWPFTableCell cell, STJc.Enum stjc) {
        // 设置垂直居中
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);

        // 设置水平居中
        setCellHorizontalAlignment(cell, stjc);

        // 设置边框
        setCellBorder(cell);
    }

    /**
     * 设置单元格水平对齐方式
     */
    private void setCellHorizontalAlignment(XWPFTableCell cell, STJc.Enum alignment) {
        if (cell.getParagraphs().size() > 0) {
            XWPFParagraph paragraph = cell.getParagraphs().get(0);
            CTP ctp = paragraph.getCTP();
            CTPPr ppr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr();
            CTJc jc = ppr.isSetJc() ? ppr.getJc() : ppr.addNewJc();
            jc.setVal(alignment);
        }
    }

    /**
     * 设置单元格边框
     */
    private void setCellBorder(XWPFTableCell cell) {
        CTTcPr tcPr = cell.getCTTc().isSetTcPr() ?
                cell.getCTTc().getTcPr() : cell.getCTTc().addNewTcPr();
        CTTcBorders borders = tcPr.isSetTcBorders() ?
                tcPr.getTcBorders() : tcPr.addNewTcBorders();

        // 设置四周边框
        CTBorder border = borders.addNewTop();
        border.setVal(STBorder.SINGLE);
        border.setSz(BigInteger.valueOf(4));
        border.setColor("000000");

        border = borders.addNewBottom();
        border.setVal(STBorder.SINGLE);
        border.setSz(BigInteger.valueOf(4));
        border.setColor("000000");

        border = borders.addNewLeft();
        border.setVal(STBorder.SINGLE);
        border.setSz(BigInteger.valueOf(4));
        border.setColor("000000");

        border = borders.addNewRight();
        border.setVal(STBorder.SINGLE);
        border.setSz(BigInteger.valueOf(4));
        border.setColor("000000");
    }

    /**
     * 设置单元格宽度
     */
    private void setCellWidth(XWPFTableCell cell, Double width) {

        CTTcPr tcPr = cell.getCTTc().isSetTcPr() ?
                cell.getCTTc().getTcPr() : cell.getCTTc().addNewTcPr();
        CTTblWidth cellWidth = tcPr.isSetTcW() ?
                tcPr.getTcW() : tcPr.addNewTcW();
        long round = Math.round(31680 * width);
        cellWidth.setW(BigInteger.valueOf(round));
        cellWidth.setType(STTblWidth.DXA);
    }

    /**
     * 设置表格样式
     */
    private void setTableStyle(XWPFTable table) {
        // 设置表格宽度为100%
        CTTblPr tblPr = table.getCTTbl().getTblPr() == null?
                table.getCTTbl().getTblPr() : table.getCTTbl().addNewTblPr();
        CTTblWidth tblWidth = tblPr.isSetTblW() ?
                tblPr.getTblW() : tblPr.addNewTblW();
        //tblWidth.setW(BigInteger.valueOf(31680));
        tblWidth.setType(STTblWidth.DXA);

        // 设置表格居中对齐
        CTJcTable jc = tblPr.isSetJc() ? tblPr.getJc() : tblPr.addNewJc();
        jc.setVal(STJcTable.CENTER);

        // 设置表格布局为自动
        CTTblLayoutType layoutType = tblPr.isSetTblLayout() ?
                tblPr.getTblLayout() : tblPr.addNewTblLayout();
        layoutType.setType(STTblLayoutType.AUTOFIT);
    }

    /**
     * 合并表格单元格（垂直方向）
     */
    private void mergeCellsVertically(XWPFTable table, int col, int startRow, int endRow) {
        if (startRow >= endRow) {
            return;
        }
        try {
            // 设置起始单元格
            XWPFTableCell startCell = table.getRow(startRow).getCell(col);
            CTTcPr tcPr = startCell.getCTTc().isSetTcPr() ?
                    startCell.getCTTc().getTcPr() : startCell.getCTTc().addNewTcPr();
            tcPr.addNewVMerge().setVal(STMerge.RESTART);

            // 设置后续单元格
            for (int i = startRow + 1; i <= endRow; i++) {
                XWPFTableCell cell = table.getRow(i).getCell(col);
                CTTcPr contPr = cell.getCTTc().isSetTcPr() ?
                        cell.getCTTc().getTcPr() : cell.getCTTc().addNewTcPr();
                contPr.addNewVMerge().setVal(STMerge.CONTINUE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
